<?php

namespace XinYaTable\Forms\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\File\Stream;

class After
{
    /**
     * 返回属性名称设置
     * @var string
     */
    public static $returnPropNameOfName    = 'code';
    public static $returnPropNameOfMessage = 'message';
    public static $returnPropNameOfData    = 'data';
    
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $_data    = null;
        $response = $next($request);
        if ($response instanceof JsonResponse) {
            if ($response->exception || $response->getStatusCode() == 500) {

                return $response;
            }
            $_data = $response->original;
        } elseif ($response instanceof Response) {
            $_data = $response->original instanceof Stream ? json_decode($response->getContent()) : $response->original;
        } else {
            $_data = $response;
        }
    
        $_response = [
            self::$returnPropNameOfName    => 0,
            self::$returnPropNameOfMessage => '请求成功',
            self::$returnPropNameOfData    => $_data,
        ];

        if (is_null($_data) || empty($_data)) {
            $_response['data'] = new \stdClass();
        } else {
            $_response['data'] = $_data;
        }
        if ($response instanceof JsonResponse) {
            $response->setData($_response);
        } elseif ($response instanceof Response) {
            $response->setContent($_response);
        }

        return $response;
    }
}
